package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.maycurobj.entity.bpm.SaleOrderEntity;
import com.maycurobj.entity.oa.HeTongEntity;
import com.maycurobj.entity.oa.ChuChaiEntity;
import com.maycurobj.entity.oa.JieKuanEntity;
import com.maycurobj.entity.oa.YiBanEntity;
import com.maycurobj.pojo.MayCurOutVoucherDataListResponse;
import com.maycurobj.repository.bpm.SaleOrderMapper;
import com.maycurobj.repository.oa.WorkflowByHeTongRepository;
import com.maycurobj.repository.oa.WorkflowByChuChaiRepository;
import com.maycurobj.repository.oa.WorkflowByJieKuanRepository;
import com.maycurobj.repository.oa.WorkflowByYiBanRepository;
import com.maycurobj.util.NormalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 外部关联单据处理服务
 */
@Service
@Slf4j
public class OutVoucherService {

    @Autowired
    private WorkflowByChuChaiRepository chuChaiRepository;

    @Autowired
    private WorkflowByHeTongRepository heTongRepository;

    @Autowired
    private SaleOrderMapper saleOrderMapper;

    @Autowired
    private WorkflowByYiBanRepository yiBanRepository;

    @Autowired
    private WorkflowByJieKuanRepository jieKuanRepository;

    static final String oaurl="https://oa.biosan.cn";

    /**
     * 返回请求的外部关联单据列表
     *
     * @param curPage  当前页
     * @param pageSize 页面记录数量

    public void getVoucherList(MayCurOutVoucher voucher, int curPage, int pageSize) {
        // 每刻 对应 OA流程是多对多情况，最终返回时，把所有相关流程都混合到一个list请求中。
        //每刻请求的流程type
        String maycurVType = voucher.getVoucherCode();
        String employeeid = voucher.getEmployeeId();

        //分页对象
        Pageable pageable = PageRequest.of(curPage, pageSize);
        //转换字典
        Map<String, Object> map = new HashMap<>();
        map.put("FT2112041IRBMKG0", null);
        //对公合同流程 -- 对公付款（每刻）
        map.put("FT21102113QWJ3EO", null);
        //会议申请流程 -- 借款申请（每刻）
        map.put("FT2111271PQCOYDC", null);
        //出差总结流程 --- 差旅报销流程（每刻,可能不要）
        map.put("FT211022135KYUPS", null);
        if(map.containsKey(maycurVType)){
            //可以转换
            log.info(JSONObject.toJSONString(map.get(maycurVType)));
        }

        //数据库请求对应结果，分页
        //返回结果list
    }
    */

    /**
     * 每刻出差审批流程对应 oa的出差流程 FT211022135KYUPS (取消)
     * 包含分页
     * @param employeeId
     * @param pageable
     * @return
     */
    public Map<String,Object> getChuChaiWF(String employeeId, String keyWord, Pageable pageable) {
        Map<String, Object> returnMap = new HashMap<>();
        //获取全部记录数量
        int countSize = this.chuChaiRepository.getCounts(employeeId,keyWord);
        List<ChuChaiEntity> chuChaiEntities = this.chuChaiRepository.getWFs(employeeId, keyWord,pageable);
        List<MayCurOutVoucherDataListResponse> lists = new ArrayList<>();
        if (chuChaiEntities.size() > 0) {
            for (ChuChaiEntity entity : chuChaiEntities) {
                //转DataListResponse
                MayCurOutVoucherDataListResponse data = new MayCurOutVoucherDataListResponse();
                //流程编号
                data.setFormDataCode(entity.getLiuchengbh());
                //事由
                data.setFormName(entity.getBiaoti());
                //操作人
                data.setSubmitUser(entity.getCaozuor());
                //时间戳
                data.setSubmitData(NormalUtil.dateToLong(entity.getShenqingrq()));
                //金额
                Map<String, Object> mapAmount = new HashMap<>();
                mapAmount.put("currency", "CNY");
                mapAmount.put("amount", Double.valueOf(entity.getJine()));
                data.setFormAmount(mapAmount);
                //url
                String _url=oaurl+"/login/maycurwfInfo.jsp?requestid="+entity.getRequestid()+"&userid=meikets";
                data.setUrl(_url);
                lists.add(data);
            }
            returnMap.put("dataList", lists);
            returnMap.put("recordsTotal", countSize);
        }
        log.info("出差总结返回list:{}", JSONObject.toJSONString(returnMap));
        return returnMap;
    }

    /**
     * 每刻对公付款审批流程对应 oa的合同流程 FT21102113QWJ3EO
     * OA 的流程没有归档 是无法被选择到的
     * 包含分页
     * 修改记录：2024-05-11，修改OA的分页，舍弃OA的分页方法，便于拼接BPM及OA的数据，之后再进行分页
     * @param employeeId
     * @param pageable
     * @return
     */
    public Map<String,Object> getHeTongWF(String employeeId, String keyWord,Pageable pageable) {
        Map<String, Object> returnMap = new HashMap<>();
        List<MayCurOutVoucherDataListResponse> lists = new ArrayList<>();

        //先获取OA的数据
        //获取OA的数据总数量
        int orderCountOA = this.heTongRepository.getCount(employeeId,keyWord);
        //设置最大的分页参数，使OA的sql查询所有流程数据
        //List<HeTongEntity> heTongEntities = this.heTongRepository.getWFs(employeeId, keyWord,pageable);
        Pageable pageableOA = PageRequest.of(0, 10000);
        List<HeTongEntity> heTongEntities = this.heTongRepository.getWFs(employeeId, keyWord,pageableOA);

        if (heTongEntities.size() > 0) {
            for (HeTongEntity entity : heTongEntities) {
                //转DataListResponse
                MayCurOutVoucherDataListResponse data = new MayCurOutVoucherDataListResponse();
                //流程编号
                data.setFormDataCode(entity.getLiuchengbh());
                //事由
                data.setFormName(entity.getBiaoti());
                data.setSubmitUser(entity.getCaozuor());
                //时间戳
                data.setSubmitData(NormalUtil.dateToLong(entity.getShenqingrq()));
                //金额
                Map<String, Object> mapAmount = new HashMap<>();
                mapAmount.put("currency", "CNY");
                mapAmount.put("amount", Double.valueOf(entity.getJine()));
                data.setFormAmount(mapAmount);
                //url
                String _url=oaurl+"/login/maycurwfInfo.jsp?requestid="+entity.getRequestid()+"&userid=meikets";
                data.setUrl(_url);
                lists.add(data);
            }
        }

        //再获取BPM的数据
        int orderCountBPM = this.saleOrderMapper.getCount(employeeId,keyWord);
        List<SaleOrderEntity> saleOrderEntities = this.saleOrderMapper.getData(employeeId,keyWord);
        if(saleOrderEntities.size()>0){
            for(SaleOrderEntity saleOrderEntity : saleOrderEntities){
                //转DataListResponse
                MayCurOutVoucherDataListResponse data = new MayCurOutVoucherDataListResponse();
                //流程编号
                data.setFormDataCode(saleOrderEntity.getSequenceNo());
                //事由
                data.setFormName(saleOrderEntity.getTitle()+"-（流程号："+saleOrderEntity.getSequenceNo()+"）");
                data.setSubmitUser(saleOrderEntity.getName());
                //时间戳
                data.setSubmitData(NormalUtil.dateToLong(saleOrderEntity.getCreatedTime()));
                //金额
                Map<String, Object> mapAmount = new HashMap<>();
                mapAmount.put("currency", "CNY");
                mapAmount.put("amount", Double.valueOf(saleOrderEntity.getOrderTotalPrice()));
                data.setFormAmount(mapAmount);
                //url
                String _url="https://bpm.biosan.cn/form/detail?workflowInstanceId="+saleOrderEntity.getWorkflowInstanceId();
                data.setUrl(_url);
                lists.add(data);

            }

        }

        //将合并结果根据时间戳重新降序排列
        lists.sort(Comparator.comparing(MayCurOutVoucherDataListResponse::getSubmitData).reversed());

        //结果分页
        int page = pageable.getPageNumber()+1;
        int countSize = pageable.getPageSize();
        int listSize = lists.size();
        int pageCount = listSize/countSize;
        int fromIndex = countSize*(page-1);
        int toIndex = fromIndex+countSize;
        if(toIndex >= listSize){
            toIndex = listSize;
        }
        if(page > pageCount+1){
            fromIndex = 0;
            toIndex = 0;
        }

        returnMap.put("dataList", lists.subList(fromIndex,toIndex));
        returnMap.put("recordsTotal", lists.size());
        log.info("对公付款（合同+BPM订单）返回list:{}", JSONObject.toJSONString(returnMap));

        return returnMap;
    }

    /**
     * 每刻一般付款审批流程对应 oa的会议流程 FT211022144CQR5S
     * 包含分页
     * @param employeeId
     * @param pageable
     * @return
     */
    public Map<String,Object> getYiBanWF(String employeeId,String keyWord, Pageable pageable) {
        Map<String, Object> returnMap = new HashMap<>();
        //获取全部数据
        int countSize = this.yiBanRepository.getCounts(employeeId,keyWord);
        //获取分页内数据
        List<YiBanEntity> yiBanEntities = this.yiBanRepository.getWFs(employeeId,keyWord, pageable);
        List<MayCurOutVoucherDataListResponse> lists = new ArrayList<>();
        if (yiBanEntities.size() > 0) {
            for (YiBanEntity entity : yiBanEntities) {
                //转DataListResponse
                MayCurOutVoucherDataListResponse data = new MayCurOutVoucherDataListResponse();
                //流程编号
                data.setFormDataCode(entity.getLiuchengbh());
                //事由
                data.setFormName(entity.getBiaoti());
                data.setSubmitUser(entity.getCaozuor());
                //时间戳
                data.setSubmitData(NormalUtil.dateToLong(entity.getShenqingrq()));
                //金额
                Map<String, Object> mapAmount = new HashMap<>();
                mapAmount.put("currency", "CNY");
                mapAmount.put("amount", Double.valueOf(entity.getJine()));
                data.setFormAmount(mapAmount);
                //url
                String _url=oaurl+"/login/maycurwfInfo.jsp?requestid="+entity.getRequestid()+"&userid=meikets";
                data.setUrl(_url);
                lists.add(data);
            }
            returnMap.put("dataList", lists);
            returnMap.put("recordsTotal", countSize);
        }
        log.info("一般付款返回list:{}", JSONObject.toJSONString(returnMap));

        return returnMap;
    }


    /**
     * 每刻借款审批流程对应 oa的会议借款+保证金借款等 FT2111271PQCOYDC
     * 包含分页
     * @param employeeId
     * @param pageable
     * @return
     */
    public Map<String,Object> getJieKuanWF(String employeeId,String keyWord, Pageable pageable) {
        Map<String, Object> returnMap = new HashMap<>();
        //获取全部数据
        int countSize = this.jieKuanRepository.getCounts(employeeId,keyWord);
        //获取分页内数据
        List<JieKuanEntity> jieKuanEntities = this.jieKuanRepository.getWFs(employeeId,keyWord, pageable);
        List<MayCurOutVoucherDataListResponse> lists = new ArrayList<>();
        if (jieKuanEntities.size() > 0) {
            for (JieKuanEntity entity : jieKuanEntities) {
                //转DataListResponse
                MayCurOutVoucherDataListResponse data = new MayCurOutVoucherDataListResponse();
                //流程编号
                data.setFormDataCode(entity.getLiuchengbh());
                //事由
                data.setFormName(entity.getBiaoti());
                data.setSubmitUser(entity.getCaozuor());
                //时间戳
                data.setSubmitData(NormalUtil.dateToLong(entity.getShenqingrq()));
                //金额
                Map<String, Object> mapAmount = new HashMap<>();
                mapAmount.put("currency", "CNY");
                mapAmount.put("amount", Double.valueOf(entity.getJine()));
                data.setFormAmount(mapAmount);
                //url
                String _url=oaurl+"/login/maycurwfInfo.jsp?requestid="+entity.getRequestid()+"&userid=meikets";
                data.setUrl(_url);
                lists.add(data);
            }
            returnMap.put("dataList", lists);
            returnMap.put("recordsTotal", countSize);
        }
        log.info("借款审批返回list:{}", JSONObject.toJSONString(returnMap));

        return returnMap;
    }

}
